package persistencia;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import modeloDatos.Valor;



public class DAOValor {
private Connection conn;
	
	public DAOValor() {
    	
    }	
	public void finalize(){
		ConnectionManager.getInstance().checkIn(conn);
    }
	
	
	public List<Valor> valoresExistentes(){
		conn = ConnectionManager.getInstance().checkOut();
		PreparedStatement stmt = null;
		String sql = "SELECT * FROM valor";
        ResultSet result = null;
        List<Valor> valores = new LinkedList<Valor>();
		try {
			stmt = conn.prepareStatement(sql);
			result = stmt.executeQuery();
			while (result.next()) {
				int id = result.getInt("idValor");
				String d = result.getString("descripcion");
				valores.add(new Valor(id,d));
			}
		} catch (SQLException ex) {
			System.out.println("Message: " + ex.getMessage());
			System.out.println("SQLState: " + ex.getSQLState());
			System.out.println("ErrorCode: " + ex.getErrorCode());
		} finally {
			finalize();
			try {
				if (result != null) {
					result.close();
				}
				if (stmt != null) {
					stmt.close();
				}
			} catch (SQLException ex) {
			}
		}
		return valores;
	}
	public Valor getIdValor(String descripcion) {
		conn = ConnectionManager.getInstance().checkOut();
		PreparedStatement stmt = null;
		String sql = "SELECT * FROM valor WHERE descripcion=?";
		ResultSet result = null;
		Valor resultado = null;
		try {
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, descripcion);
			result = stmt.executeQuery();
			if(result.next()) {
				resultado = new Valor(result.getInt("idValor"),descripcion);
				
			}
		} catch (SQLException ex) {
			System.out.println("Message: " + ex.getMessage());
			System.out.println("SQLState: " + ex.getSQLState());
			System.out.println("ErrorCode: " + ex.getErrorCode());
		} finally {
			finalize();
			try {
				if (result != null) {
					result.close();
				}
				if (stmt != null) {
					stmt.close();
				}
			} catch (SQLException ex) {
			}
		}
		return resultado;
	}
}
